package juc.lock;

import java.util.concurrent.locks.AbstractQueuedSynchronizer;


public class MyLock extends AbstractQueuedSynchronizer {
    @Override
    protected boolean tryAcquire(int arg) {
        if(compareAndSetState(0,1)){
            setExclusiveOwnerThread(Thread.currentThread());
            return true;
        }
        return false;
    }

    @Override
    protected boolean tryRelease(int arg) {
        setExclusiveOwnerThread(null);
        setState(0);
        return true;
    }

    public boolean tryLock(){
        return tryAcquire(1);
    }

    public void lock(){
       acquire(1);
    }

    public void unLock(){
        release(0);
    }

    public boolean isLocked(){
        return isHeldExclusively();
    }

}
